<!DOCTYPE html>


<html lang="en">


<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    springboot中dubbo服务导出-3 |  一曲秋殇
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/images/myfavicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-dubbo/springboot中dubbo服务导出-3"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  springboot中dubbo服务导出-3
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/dubbo/springboot%E4%B8%ADdubbo%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA-3/" class="article-date">
  <time datetime="2021-12-13T05:51:40.041Z" itemprop="datePublished">2021-12-13</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E5%90%8E%E5%8F%B0/">后台</a> / <a class="article-category-link" href="/categories/%E5%90%8E%E5%8F%B0/java/">java</a> / <a class="article-category-link" href="/categories/%E5%90%8E%E5%8F%B0/java/dubbo/">dubbo</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">2.3k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">10 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/hint.css/2.4.1/hint.min.css"><blockquote>
<p>上一篇<a href="/dubbo/springboot%E4%B8%ADdubbo%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA-2/">“springboot中dubbo服务导出-2”</a>分析了RegistryProtocol#export方法前半部分方法服务启动，这一篇主要分析该方法下半部分远程服务注册<br>以下分析是基于dubbo2.7.8</p>
</blockquote>
<p> 此处再次贴出RegistryProtocol#export方法体代码<br>  <figure class="highlight java"><figcaption><span>RegistryProtocol.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">  <span class="keyword">public</span> &lt;T&gt; <span class="function">Exporter&lt;T&gt; <span class="title">export</span><span class="params">(<span class="keyword">final</span> Invoker&lt;T&gt; originInvoker)</span> <span class="keyword">throws</span> RpcException </span>&#123;</span><br><span class="line">      URL registryUrl = getRegistryUrl(originInvoker);</span><br><span class="line">      URL providerUrl = getProviderUrl(originInvoker);</span><br><span class="line">      <span class="keyword">final</span> URL overrideSubscribeUrl = getSubscribedOverrideUrl(providerUrl);</span><br><span class="line">      <span class="keyword">final</span> OverrideListener overrideSubscribeListener = <span class="keyword">new</span> OverrideListener(overrideSubscribeUrl, originInvoker);</span><br><span class="line">      overrideListeners.put(overrideSubscribeUrl, overrideSubscribeListener);</span><br><span class="line">      providerUrl = overrideUrlWithConfig(providerUrl, overrideSubscribeListener);</span><br><span class="line">      <span class="keyword">final</span> ExporterChangeableWrapper&lt;T&gt; exporter = doLocalExport(originInvoker, providerUrl);</span><br><span class="line">      <span class="comment">//----------------------------------------------分割线，前面是服务启动相关，下面是注册到注册中心相关-------------------------------------------------------------------</span></span><br><span class="line">      <span class="keyword">final</span> Registry registry = getRegistry(originInvoker);</span><br><span class="line">      <span class="keyword">final</span> URL registeredProviderUrl = getUrlToRegistry(providerUrl, registryUrl);</span><br><span class="line">      <span class="keyword">boolean</span> register = providerUrl.getParameter(REGISTER_KEY, <span class="keyword">true</span>);</span><br><span class="line">      <span class="keyword">if</span> (register) &#123;</span><br><span class="line">          register(registryUrl, registeredProviderUrl);</span><br><span class="line">      &#125;</span><br><span class="line">      registerStatedUrl(registryUrl, registeredProviderUrl, register);</span><br><span class="line">      exporter.setRegisterUrl(registeredProviderUrl);</span><br><span class="line">      exporter.setSubscribeUrl(overrideSubscribeUrl);</span><br><span class="line">      registry.subscribe(overrideSubscribeUrl, overrideSubscribeListener);</span><br><span class="line">      notifyExport(exporter);</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> DestroyableExporter&lt;&gt;(exporter);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure><br>  下面对RegistryProtocol#export方法中后半部分代码进行详细分析</p>
<h4 id="1-执行RegistryProtocol-getRegistry方法获取Registry对象"><a href="#1-执行RegistryProtocol-getRegistry方法获取Registry对象" class="headerlink" title="1. 执行RegistryProtocol#getRegistry方法获取Registry对象"></a>1. 执行RegistryProtocol#getRegistry方法获取Registry对象</h4><hr>
<p>RegistryProtocol#getRegistry这个方法里面的逻辑主要是创建Registry对象（在创建该对象的过程中会连接注册中心，像zookeeper最终创建的就是一个ZookeeperRegistry对象）<br>getRegistry方法代码如下：</p>
<figure class="highlight java"><figcaption><span>RegistryProtocol.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> Registry <span class="title">getRegistry</span><span class="params">(<span class="keyword">final</span> Invoker&lt;?&gt; originInvoker)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//getRegistryUrl在服务导出-2中分析过了，主要是替换协议为zookeeper，然后转为URL对象，替换后的URL如下所示</span></span><br><span class="line">    <span class="comment">//zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=c3-provider&amp;dubbo=2.0.2&amp;export=dubbo%3A%2F%2F192.168.10.120%3A20880%2Fcom.alibaba.dubbo.demo.DemoService%3Fanyhost%3Dtrue%26application%3Dc3-provider%26bind.ip%3D192.168.10.120%26bind.port%3D20880%26default%3Dtrue%26deprecated%3Dfalse%26dubbo%3D2.0.2%26dynamic%3Dtrue%26generic%3Dfalse%26interface%3Dcom.alibaba.dubbo.demo.DemoService%26metadata-type%3Dremote%26methods%3DsayHello%26pid%3D2508%26qos.enable%3Dfalse%26release%3D2.7.8%26side%3Dprovider%26timestamp%3D1614828359691&amp;pid=2508&amp;qos.enable=false&amp;release=2.7.8&amp;timestamp=1614828359691</span></span><br><span class="line">    URL registryUrl = getRegistryUrl(originInvoker);</span><br><span class="line">    <span class="comment">//通过自适应拓展registryFactory对象获取注册实例，这个registryFactory对象是在加载RegistryProtocol这个拓展实现的时候通过ioc注入进来的，ico部分可通过下面的链接查看</span></span><br><span class="line">    <span class="comment">//由于使用的是zookeeper协议作为注册中心，所以拓展实现是ZookeeperRegistryFactory对象，ZookeeperRegistryFactory#getRegistry方法下面再展开分析</span></span><br><span class="line">    <span class="keyword">return</span> registryFactory.getRegistry(registryUrl);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>ioc部分可查看<a href="/dubbo/dubbo%E8%87%AA%E9%80%82%E5%BA%94%E6%8B%93%E5%B1%95/#2-%E8%8E%B7%E5%8F%96Protocol%E7%B1%BB%E7%9A%84%E8%87%AA%E9%80%82%E5%BA%94%E6%8B%93%E5%B1%95%E5%AF%B9%E8%B1%A1">dubbo自适应拓展3.2</a></p>
</blockquote>
<p>ZookeeperRegistryFactory#getRegistry(URL url)方法是在其父类AbstractRegistryFactory中（该类是对注册工厂的抽象，像ConsulRegistryFactory、RedisRegistryFactory等其他注册工厂都继承自他），代码如下</p>
<figure class="highlight java"><figcaption><span>AbstractRegistryFactory.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> Registry <span class="title">getRegistry</span><span class="params">(URL url)</span> </span>&#123;</span><br><span class="line">     <span class="keyword">if</span> (destroyed.get()) &#123;</span><br><span class="line">         <span class="keyword">return</span> DEFAULT_NOP_REGISTRY;</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="comment">//重新构建了一个url，格式如下</span></span><br><span class="line">     <span class="comment">//zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=c3-provider&amp;dubbo=2.0.2&amp;interface=org.apache.dubbo.registry.RegistryService&amp;pid=6228&amp;qos.enable=false&amp;release=2.7.8&amp;timestamp=1615938846911</span></span><br><span class="line">     url = URLBuilder.from(url)</span><br><span class="line">             <span class="comment">//修改path值为&quot;org.apache.dubbo.registry.RegistryService&quot;</span></span><br><span class="line">             .setPath(RegistryService.class.getName())</span><br><span class="line">             <span class="comment">//添加了参数interface值为&quot;org.apache.dubbo.registry.RegistryService&quot;</span></span><br><span class="line">             .addParameter(INTERFACE_KEY, RegistryService.class.getName())</span><br><span class="line">             <span class="comment">//移除url中export和refer两个参数</span></span><br><span class="line">             .removeParameters(EXPORT_KEY, REFER_KEY)</span><br><span class="line">             .build();</span><br><span class="line">     <span class="comment">//获取的key大概长下面这个样子</span></span><br><span class="line">     <span class="comment">//zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService</span></span><br><span class="line">     String key = createRegistryCacheKey(url);</span><br><span class="line">     LOCK.lock();</span><br><span class="line">     <span class="keyword">try</span> &#123;</span><br><span class="line">         <span class="comment">//先从缓存中去取，从key中可以看出，同一个注册协议相同端口只会创建一个Registry对象</span></span><br><span class="line">         Registry registry = REGISTRIES.get(key);</span><br><span class="line">         <span class="keyword">if</span> (registry != <span class="keyword">null</span>) &#123;</span><br><span class="line">             <span class="keyword">return</span> registry;</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="comment">//这是个抽象方法，具体实现在子类ZookeeperRegistryFactory中</span></span><br><span class="line">         registry = createRegistry(url);</span><br><span class="line">         <span class="keyword">if</span> (registry == <span class="keyword">null</span>) &#123;</span><br><span class="line">             <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">&quot;Can not create registry &quot;</span> + url);</span><br><span class="line">         &#125;</span><br><span class="line">         REGISTRIES.put(key, registry);</span><br><span class="line">         <span class="keyword">return</span> registry;</span><br><span class="line">     &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">         LOCK.unlock();</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>AbstractRegistryFactory#getRegistry方法缓存中取不到Register对象则调用具体的实现类ZookeeperRegistryFactory#createRegistry方法进行创建register对象了<br>createRegistry代码如下</p>
<figure class="highlight java"><figcaption><span>ZookeeperRegistryFactory.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> ZookeeperTransporter zookeeperTransporter;</span><br><span class="line"> </span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setZookeeperTransporter</span><span class="params">(ZookeeperTransporter zookeeperTransporter)</span> </span>&#123;</span><br><span class="line">     <span class="keyword">this</span>.zookeeperTransporter = zookeeperTransporter;</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> Registry <span class="title">createRegistry</span><span class="params">(URL url)</span> </span>&#123;</span><br><span class="line">     <span class="comment">//这里的zookeeperTransporter的值是加载ZookeeperRegistryFactory这个拓展的时候通过ioc进行设置的</span></span><br><span class="line">     <span class="comment">//ZookeeperTransporter也是个自适应拓展，默认的拓展实现为curator（即 CuratorZookeeperTransporter）</span></span><br><span class="line">     <span class="keyword">return</span> <span class="keyword">new</span> ZookeeperRegistry(url, zookeeperTransporter);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>上面的createRegistry方法最终通过实例化了一个ZookeeperRegistry对象，该对象的构造方法如下</p>
<figure class="highlight java"><figcaption><span>ZookeeperRegistry.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ZookeeperRegistry</span><span class="params">(URL url, ZookeeperTransporter zookeeperTransporter)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//执行父类中一些公共的故障处理逻辑，主要是读取本地文件中的缓存及创建一个时间轮用于重试</span></span><br><span class="line">    <span class="keyword">super</span>(url);</span><br><span class="line">    <span class="keyword">if</span> (url.isAnyHost()) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">&quot;registry address == null&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    String group = url.getParameter(GROUP_KEY, DEFAULT_ROOT);</span><br><span class="line">    <span class="keyword">if</span> (!group.startsWith(PATH_SEPARATOR)) &#123;</span><br><span class="line">        group = PATH_SEPARATOR + group;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">this</span>.root = group;</span><br><span class="line">    <span class="comment">//连接注册中心创建ZookeeperClient（zookeeperTransporter为自适应拓展类，默认实现为 CuratorZookeeperTransporter）</span></span><br><span class="line">    <span class="comment">//在 CuratorZookeeperTransporter 类中主要是实例化了一个CuratorZookeeperClient对象进行返回，并且该CuratorZookeeperClient对象会被缓存下来，key为url中的ip+端口</span></span><br><span class="line">    zkClient = zookeeperTransporter.connect(url);</span><br><span class="line">    <span class="comment">//为客户端添加连接状态变更监听（在CuratorZookeeperClient的构造中有往注册中心添加一个CuratorConnectionStateListener监听器，该监听器的stateChanged方法中会通知此处添加的监听）</span></span><br><span class="line">    zkClient.addStateListener((state) -&gt; &#123;</span><br><span class="line">        <span class="keyword">if</span> (state == StateListener.RECONNECTED) &#123;</span><br><span class="line">            <span class="comment">//在连接超时但没有达到会话超时时间会调用此方法</span></span><br><span class="line">            ZookeeperRegistry.<span class="keyword">this</span>.fetchLatestAddresses();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (state == StateListener.NEW_SESSION_CREATED) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">//在连接超时且达到了会话超时时间会调用此方法</span></span><br><span class="line">                ZookeeperRegistry.<span class="keyword">this</span>.recover();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                logger.error(e.getMessage(), e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (state == StateListener.SESSION_LOST) &#123;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (state == StateListener.SUSPENDED) &#123;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (state == StateListener.CONNECTED) &#123;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面ZookeeperRegistr首先调用父类FailbackRegistry构造的时候创建了一个HashedWheelTimer时间轮对象</p>
<figure class="highlight java"><figcaption><span>FailbackRegistry.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">FailbackRegistry</span><span class="params">(URL url)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>(url);</span><br><span class="line">    <span class="comment">//取出url中retry.period参数的值作为下面时间轮的跳动一次的时间间隔</span></span><br><span class="line">    <span class="keyword">this</span>.retryPeriod = url.getParameter(REGISTRY_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_RETRY_PERIOD);</span><br><span class="line">    <span class="comment">//创建一个时间轮，关于时间轮的内容可查看下面的链接</span></span><br><span class="line">    retryTimer = <span class="keyword">new</span> HashedWheelTimer(<span class="keyword">new</span> NamedThreadFactory(<span class="string">&quot;DubboRegistryRetryTimer&quot;</span>, <span class="keyword">true</span>), retryPeriod, TimeUnit.MILLISECONDS, <span class="number">128</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>HashedWheelTimer对时间轮实现的数据结构大概如下面这个样子<br><img src="http://img.luobiao.vip/img/20210322001034.jpg"></p>
<blockquote>
<p>直接看HashedWheelTimer中的代码会比较吃力，下面贴出一个时间轮的简单实现<br><a target="_blank" rel="noopener" href="https://gitee.com/luobiao320/demo/blob/master/src/main/java/thread/wang_bao_ling/c22/executors/wheel/Test.java">简单时间轮实现代码</a></p>
</blockquote>
<h4 id="2-获取最终注册到注册中心的url"><a href="#2-获取最终注册到注册中心的url" class="headerlink" title="2.获取最终注册到注册中心的url"></a>2.获取最终注册到注册中心的url</h4><p>这一步主要是获取注册到注册中心的url，供后面写入注册中心使用</p>
<figure class="highlight java"><figcaption><span>RegistryProtocol.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> URL <span class="title">getUrlToRegistry</span><span class="params">(<span class="keyword">final</span> URL providerUrl, <span class="keyword">final</span> URL registryUrl)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!registryUrl.getParameter(SIMPLIFIED_KEY, <span class="keyword">false</span>)) &#123;</span><br><span class="line">        <span class="comment">//默认没有配置dubbo.registry.simplified=true的时候注册到注册中心的地址就是通过providerUrl移除一些key后的结果，结果大概如下</span></span><br><span class="line">        <span class="comment">//dubbo://192.168.56.1:20880/com.study.api.OrderService?anyhost=true&amp;application=c3-provider&amp;default=true&amp;deprecated=false&amp;dubbo=2.0.2&amp;dynamic=true&amp;generic=false&amp;interface=com.study.api.OrderService&amp;metadata-type=remote&amp;methods=getOrder&amp;pid=8136&amp;release=2.7.8&amp;side=provider&amp;timestamp=1616453826329</span></span><br><span class="line">        <span class="keyword">return</span> providerUrl.removeParameters(getFilteredKeys(providerUrl)).removeParameters(</span><br><span class="line">                MONITOR_KEY, BIND_IP_KEY, BIND_PORT_KEY, QOS_ENABLE, QOS_HOST, QOS_PORT, ACCEPT_FOREIGN_IP, VALIDATION_KEY,</span><br><span class="line">                INTERFACES);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">//有配置dubbo.registry.simplified=true则说明使用元数据中心，使用元数据中心的话处理添加这个配置还需要做如下两个操作</span></span><br><span class="line">        <span class="comment">//1.增加metadata-report配置</span></span><br><span class="line">        <span class="comment">//2.增加@Servcie(parameters=&#123;“metadata”,“remote”&#125;)或者@Reference(parameters=&#123;“metadata”,“remote”&#125;)，否则无法使用远程元数据中心</span></span><br><span class="line">        String extraKeys = registryUrl.getParameter(EXTRA_KEYS_KEY, <span class="string">&quot;&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span> (!providerUrl.getPath().equals(providerUrl.getParameter(INTERFACE_KEY))) &#123;</span><br><span class="line">            <span class="keyword">if</span> (StringUtils.isNotEmpty(extraKeys)) &#123;</span><br><span class="line">                extraKeys += <span class="string">&quot;,&quot;</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            extraKeys += INTERFACE_KEY;</span><br><span class="line">        &#125;</span><br><span class="line">        String[] paramsToRegistry = getParamsToRegistry(DEFAULT_REGISTER_PROVIDER_KEYS</span><br><span class="line">                , COMMA_SPLIT_PATTERN.split(extraKeys));</span><br><span class="line">        <span class="keyword">return</span> URL.valueOf(providerUrl, paramsToRegistry, providerUrl.getParameter(METHODS_KEY, (String[]) <span class="keyword">null</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="3-执行RegistryProtocol-register方法将需要注册的服务url写入到注册中心"><a href="#3-执行RegistryProtocol-register方法将需要注册的服务url写入到注册中心" class="headerlink" title="3.执行RegistryProtocol#register方法将需要注册的服务url写入到注册中心"></a>3.执行RegistryProtocol#register方法将需要注册的服务url写入到注册中心</h4><p>RegistryProtocol#register方法代码如下：</p>
<figure class="highlight java"><figcaption><span>RegistryProtocol.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">register</span><span class="params">(URL registryUrl, URL registeredProviderUrl)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//获取1中创建的Registry（改值已被缓存下来了，直接从缓存中可以获取）</span></span><br><span class="line">    Registry registry = registryFactory.getRegistry(registryUrl);</span><br><span class="line">    <span class="comment">//调用Registry#register方法执行创建操作</span></span><br><span class="line">    registry.register(registeredProviderUrl);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的Registry#register方法调用最终会进入FailbackRegistry#register，方法代码如下</p>
<figure class="highlight java"><figcaption><span>FailbackRegistry.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">register</span><span class="params">(URL url)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!acceptable(url)) &#123;</span><br><span class="line">        logger.info(<span class="string">&quot;URL &quot;</span> + url + <span class="string">&quot; will not be registered to Registry. Registry &quot;</span> + url + <span class="string">&quot; does not accept service of this protocol type.&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//这一步主要是执行将注册的url写入到一个Set中进行缓存</span></span><br><span class="line">    <span class="keyword">super</span>.register(url);</span><br><span class="line">    removeFailedRegistered(url);</span><br><span class="line">    removeFailedUnregistered(url);</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">//调用doRegister执行注册，该方法是个抽象方法，由具体的注册中心实现，此处是ZookeeperRegistry#doRegister</span></span><br><span class="line">        doRegister(url);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">     </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ZookeeperRegistry#doRegister方法代码如下：</p>
<figure class="highlight java"><figcaption><span>ZookeeperRegistry</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doRegister</span><span class="params">(URL url)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">//先调用toUrlPath方法生成最终写入到注册中心的路径，格式为dubbo+服务接口名称+providers+encode的url，最终生成的路径如下</span></span><br><span class="line">        <span class="comment">//dubbo/com.study.api.UserService/providers/dubbo%3A%2F%2F192.168.56.1%3A20880%2Fcom.study.api.UserService%3Fanyhost%3Dtrue%26application%3Dc3-provider%26default%3Dtrue%26deprecated%3Dfalse%26dubbo%3D2.0.2%26dynamic%3Dtrue%26generic%3Dfalse%26interface%3Dcom.study.api.UserService%26metadata-type%3Dremote%26methods%3DgetUserList%26pid%3D1576%26release%3D2.7.8%26side%3Dprovider%26timestamp%3D1616455562378</span></span><br><span class="line">        <span class="comment">//生成完路径后就调用CuratorZookeeperClient#create去注册中心执行创建该路径的操作了</span></span><br><span class="line">        zkClient.create(toUrlPath(url), url.getParameter(DYNAMIC_KEY, <span class="keyword">true</span>));</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RpcException(<span class="string">&quot;Failed to register &quot;</span> + url + <span class="string">&quot; to zookeeper &quot;</span> + getUrl() + <span class="string">&quot;, cause: &quot;</span> + e.getMessage(), e);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="4-调用RegistryProtocol-notifyExport执行服务发布成功通知"><a href="#4-调用RegistryProtocol-notifyExport执行服务发布成功通知" class="headerlink" title="4.调用RegistryProtocol#notifyExport执行服务发布成功通知"></a>4.调用RegistryProtocol#notifyExport执行服务发布成功通知</h4><p>RegistryProtocol#notifyExport方法如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> &lt;T&gt; <span class="function"><span class="keyword">void</span> <span class="title">notifyExport</span><span class="params">(ExporterChangeableWrapper&lt;T&gt; exporter)</span> </span>&#123;</span><br><span class="line">    List&lt;RegistryProtocolListener&gt; listeners = ExtensionLoader.getExtensionLoader(RegistryProtocolListener.class)</span><br><span class="line">            .getActivateExtension(exporter.getOriginInvoker().getUrl(), <span class="string">&quot;registry.protocol.listener&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span> (CollectionUtils.isNotEmpty(listeners)) &#123;</span><br><span class="line">        <span class="keyword">for</span> (RegistryProtocolListener listener : listeners) &#123;</span><br><span class="line">            listener.onExport(<span class="keyword">this</span>, exporter);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>从上面的方法我们如果想监听服务发布成功的事件则可以自定义一个类去实现RegistryProtocolListener接口，然后添加到自定义拓展中就行了</p>
<p>至此dubbo服务导出基本上就完成了，最终返回了一个DestroyableExporter对象</p>
<link rel="stylesheet" href="/css/spoiler.css" type="text/css"><script src="/js/spoiler.js" type="text/javascript" async></script> 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://luobiao320.gitee.io/dubbo/springboot%E4%B8%ADdubbo%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA-3/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/dubbo/" rel="tag">dubbo</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/springboot/" rel="tag">springboot</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA/" rel="tag">服务导出</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/dubbo/dubbo%E8%87%AA%E9%80%82%E5%BA%94%E6%8B%93%E5%B1%95/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            dubbo自适应拓展
          
        </div>
      </a>
    
    
      <a href="/dubbo/springboot%E4%B8%ADdubbo%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA-2/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">springboot中dubbo服务导出-2</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "kHx6wceVXdEyiCrLm0sLAwoF-gzGzoHsz",
    app_key: "ArEdGk6wzHOhrXLiwmClhDNH",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2020-2021
        <i class="ri-heart-fill heart_icon"></i> luobiao
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        Powered by <a href="https://hexo.io" target="_blank">Hexo</a>
        <span class="division">|</span>
        Theme - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      
        <li>
          <a href="http://beian.miit.gov.cn/" target="_black" rel="nofollow">赣ICP备2020014719号-1</a>
        </li>
        
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="http://img.luobiao.vip/53119d0bda706bbe350333137a67ea3e_1.jpg" alt="一曲秋殇"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/dubbo">dubbo</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/spring">spring</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/mysql">mysql</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->

<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>